/*
 * Copyright (c) 2016. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.tsinghuabigdata.edu.ddmath.module.mycenter;

import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
import com.tsinghuabigdata.edu.commons.cache.CacheManager;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.bean.UserDetailinfo;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.AppLog;
import com.tsinghuabigdata.edu.ddmath.util.AssertUtils;
import com.tsinghuabigdata.edu.ddmath.util.HeadImageUtils;

import java.lang.reflect.Method;
import java.util.regex.Pattern;

import roboguice.util.Strings;

/**
 * 设置头像显示到ImageView
 * Created by yanshen on 2016/4/7.
 */
public class SetHeadImage {

    public static void loadHeadImage(Context context, ImageView imageView, String headImage) {
        if (Strings.isEmpty(headImage)) {
            return;
        }
        ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageView, R.drawable.personalcenter_bg_popup_photochange, R.drawable.personalcenter_bg_popup_photochange);
        ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(context), CacheManager.getBitmapLruCache());
        imageLoader.get(headImage, listener);
    }

    /**
     * 根据字符串翻译成Assets中的路径,然后设置图片显示
     *
     * @param headImage
     */
    private static void loadLocalHeadImage(Context context, ImageView imageView, String headImage) {
        String headPath = HeadImageUtils.getLocalHeadImage(headImage);
        if (headPath == null || "".equals(headPath)) {
            return;
        }
        Bitmap bitmap = AssertUtils.getImageFromAssetsFile(context.getResources(), headPath);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        }
    }

    /**
     * 设置头像
     *
     * @param context
     * @param imageView
     * @param studentInfo
     */
    public static void setHeadImage(Context context, ImageView imageView, UserDetailinfo studentInfo) {
        String headImage = studentInfo.getHeadImage();
        if (!Strings.isEmpty(headImage)) {
            if (Pattern.matches("\\{.*?\\}", headImage)) {
                // 是系统头像
                loadLocalHeadImage(context, imageView, headImage);
            } else {
                // 自定义头像
                loadHeadImage(context, imageView, studentInfo.getFileAddress() + headImage);
            }
        } else {
            //URL为空时，得到的是默认头像
            loadHeadImage(context, imageView, headImage + "error");
        }
    }

    /**
     * 设置头像
     *
     * @param context
     * @param imageView
     * @param headImage
     */
    public static void setHeadImage(Context context, ImageView imageView, String headImage) {
        if (!Strings.isEmpty(headImage)) {
            if (Pattern.matches(".*?\\{.*?\\}", headImage)) {
                // 是系统头像
                String[] arr = headImage.split("/");
                headImage = arr[arr.length - 1];
                loadLocalHeadImage(context, imageView, headImage);
            } else {
                // 自定义头像
                loadHeadImage(context, imageView, headImage);
            }
        } else {
            //URL为空时，得到的是默认头像
            imageView.setImageResource(R.drawable.personalcenter_bg_defaultface);
        }
    }

    /**
     * 设置头像
     *
     * @param context
     * @param imageView
     * @param incompleteUrl
     */
    public static void setHeadIncomplete(Context context, ImageView imageView, String incompleteUrl) {
        if (!Strings.isEmpty(incompleteUrl)) {
            if (Pattern.matches(".*?\\{.*?\\}", incompleteUrl)) {
                // 是系统头像
                String[] arr = incompleteUrl.split("/");
                incompleteUrl = arr[arr.length - 1];
                loadLocalHeadImage(context, imageView, incompleteUrl);
            } else {
                // 自定义头像
                loadHeadImage(context, imageView, AccountUtils.getLoginUser().getFileServer() + incompleteUrl);
            }
        } else {
            //URL为空时，得到的是默认头像
            imageView.setImageResource(R.drawable.personalcenter_bg_defaultface);
        }
    }

    /**
     * 设置头像
     *
     * @param context
     * @param imageView
     * @param incompleteUrl
     */
    public static void setHeadIncomplete(Context context, ImageView imageView, String incompleteUrl,int res) {
        if (!Strings.isEmpty(incompleteUrl)) {
            if (Pattern.matches(".*?\\{.*?\\}", incompleteUrl)) {
                // 是系统头像
                String[] arr = incompleteUrl.split("/");
                incompleteUrl = arr[arr.length - 1];
                loadLocalHeadImage(context, imageView,  incompleteUrl);
            } else {
                // 自定义头像
                ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageView, res, res);
                ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(context), CacheManager.getBitmapLruCache());
                imageLoader.get(AccountUtils.getLoginUser().getFileServer()+incompleteUrl, listener);
            }
        } else {
            //URL为空时，得到的是默认头像
            imageView.setImageResource(res);
        }
    }

    /**
     * 设置头像
     *
     * @param context
     * @param imageView
     * @param headImage
     */
    public static void setHeadImage(Context context, ImageView imageView, String headImage, String fileAddress) {
        if (!Strings.isEmpty(headImage)) {
            if (Pattern.matches(".*?\\{.*?\\}", headImage)) {
                // 是系统头像
                String[] arr = headImage.split("/");
                headImage = arr[arr.length - 1];
                loadLocalHeadImage(context, imageView, headImage);
            } else {
                // 自定义头像
                loadHeadImage(context, imageView, fileAddress + headImage);
            }
        } else {
            //URL为空时，得到的是默认头像
            imageView.setImageResource(R.drawable.personalcenter_bg_defaultface);
        }
    }

    /**
     * 加载网络图片
     */
    public static void loadNetImage(Context context, ImageView imageView, String fileAddress) {
        ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageView, R.drawable.ic_temporary_image,
                R.drawable.ic_broken_image);
        ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(context), CacheManager.getBitmapLruCache());
        imageLoader.get(fileAddress, listener);
    }

    /**
     * 放入缓存
     *
     * @param studentInfo
     * @param bitmap
     */
    public static void putCache(UserDetailinfo studentInfo, Bitmap bitmap) {
        try {
            String url = studentInfo.getFileAddress() + studentInfo.getHeadImage();
            // private static String getCacheKey(String url, int maxWidth, int maxHeight, ScaleType scaleType, ImageRequest.Transformation transformation)
            Method getCacheKey = ImageLoader.class.getDeclaredMethod("getCacheKey", String.class, Integer.TYPE, Integer.TYPE, ImageView.ScaleType.class, ImageRequest.Transformation.class);
            getCacheKey.setAccessible(true);
            String key = (String) getCacheKey.invoke(null, url, 0, 0, ImageView.ScaleType.CENTER_INSIDE, null);
            CacheManager.getBitmapLruCache().putBitmap(key, bitmap);
        } catch (Exception ex) {
            AppLog.i("err", ex);
        }
    }
}
